package com.blueocean_health.care.management.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blueocean_health.care.management.common.base.em.TimeType;
import com.blueocean_health.care.management.common.base.string.StringUtils;
import com.blueocean_health.care.management.common.base.time.TimeUtils;
import com.blueocean_health.care.management.common.excel.ExcelUtil;
import com.blueocean_health.care.management.domain.base.SysResult;
import com.blueocean_health.care.management.domain.base.SysResultByPage;
import com.blueocean_health.care.management.domain.dto.NurseWorkerInfoDto;
import com.blueocean_health.care.management.domain.dto.NurseWorkerInfoHealthCertResponseDto;
import com.blueocean_health.care.management.domain.dto.NurseWorkerInfoRequestDto;
import com.blueocean_health.care.management.domain.dto.NurseWorkerInfoResponseDto;
import com.blueocean_health.care.management.domain.dto.NurseWorkerListDto;
import com.blueocean_health.care.management.domain.dto.PullDownDto;
import com.blueocean_health.care.management.em.WorkerTypeEnum;
import com.blueocean_health.care.management.exception.OrderServiceException;
import com.blueocean_health.care.management.service.NurseWorkerInfoService;
import com.github.pagehelper.PageInfo;

/**
 * 护工信息 2017年10月20日15:28:32
 * 
 * @author 陆学
 *
 */
@RequestMapping("/nurse")
@RestController
public class NurseWorkerInfoController {

	@Value("classpath:template/护工模板.xlsx")
	private Resource resource;
	@Autowired
	private NurseWorkerInfoService nurseService;

	/**
	 * 更新护工表中所有护工拼音字段
	 * 
	 * @return
	 */
	@RequestMapping("/update-workername-pinyin")
	public SysResult updateWorkernamePinyin() {
		return nurseService.updateWorkernamePinyin();
	}

	/**
	 * 根据筛选条件获取护工列表 2017年10月20日15:34:23
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping("pull/list")
	public SysResult getNurseList(@RequestBody Map<String, String> map) {
		// TODO
//		ValidateUser courrentUser = LocalManager.getVal(LocalManagerType.USER_OUTWORKER);
//		map.put("hospitalId", courrentUser.getUser().getTeamId());
		List<PullDownDto> nurseList = nurseService.getNurseList(map);
		return SysResult.ok(nurseList);
	}

	/**
	 * 根据筛选条件获取护工列表 ,包含上工，待岗状态
	 * 
	 * @param map
	 * @return
	 * @throws OrderServiceException
	 */
	@RequestMapping("list/workstatus")
	public SysResult getNurseWorkerList(@RequestBody Map<String, String> map) throws OrderServiceException {
		// TODO
//		ValidateUser courrentUser = LocalManager.getVal(LocalManagerType.USER_OUTWORKER);
//		String teamId = courrentUser.getUser().getTeamId();
//		map.put("hospitalId", teamId);
		PageInfo<NurseWorkerListDto> nurseWorkerList = nurseService.getNurseWorkerListNew(map);
		nurseWorkerList.setPageNum(Integer.parseInt(map.get("page")));
		return SysResultByPage.ok(nurseWorkerList.getList(), nurseWorkerList.getTotal(), map.get("page"));
	}

	/**
	 * 获取护工列表分页
	 */
	@RequestMapping("/list")
	public SysResult findList(@RequestBody String jsonStr) {
		return nurseService.list(JSON.parseObject(jsonStr, NurseWorkerInfoRequestDto.class));
	}

	/**
	 * 导出护工Execl
	 */
	@RequestMapping("/exportNurseWorkerInfoExcel")
	public void listNurseWorkerInfoExecl(@RequestBody NurseWorkerInfoRequestDto nurseWorkerInfoRequestDto,
			HttpServletResponse response) {
		try {
			List<NurseWorkerInfoResponseDto> list = nurseService.listNurseWorkerInfoExcel(nurseWorkerInfoRequestDto);
			String finalFileName = URLEncoder.encode("护工列表_" + TimeUtils.getTime(TimeType.yyyyMMddHHmmssSSS) + ".xls",
					"UTF8");
			response.addHeader("Content-Disposition", "attachment;filename=" + finalFileName);
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			ExcelUtil.getInstance().exportObj2Excel(toClient, list, NurseWorkerInfoResponseDto.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 导出护工Execl
	 */
	@RequestMapping("/listNurseWorkerInfoExcel")
	public SysResult listNurseWorkerInfoExcel(@RequestBody NurseWorkerInfoRequestDto nurseWorkerInfoRequestDto) throws Exception {
		List<NurseWorkerInfoResponseDto> list = nurseService.listNurseWorkerInfoExcel(nurseWorkerInfoRequestDto);
		PageInfo<NurseWorkerInfoResponseDto> pageInfo = new PageInfo<NurseWorkerInfoResponseDto>(list);
		return SysResultByPage.ok(0, "SUCCESS", pageInfo.getList(), pageInfo.getTotal());
	}

	/**
	 * 下载模板
	 * 
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/exportTemplateExcel")
	public ResponseEntity<byte[]> exportTemplateExcel(HttpServletResponse response, HttpServletRequest request)
			throws IOException {
		try {
			InputStream in = resource.getInputStream();
			HttpHeaders headers = new HttpHeaders();
			headers.setContentDispositionFormData("attachment", URLEncoder.encode("护工模板.xlsx", "UTF8"));
			headers.setContentType(MediaType.valueOf("application/vnd.ms-excel"));
			return new ResponseEntity<byte[]>(FileCopyUtils.copyToByteArray(in), headers, HttpStatus.OK);
		} catch (Exception e) {
			throw new RuntimeException("模板文件下载失败" + e + resource);
		}
	}

	/**
	 * 批量导入护工基本信息
	 */
	@RequestMapping("/importNurseExcel")
	public SysResult importNurseExcel(HttpServletRequest request) {
		// TODO
//		// 设置医院
//		User user = LocalManager.getVal(LocalManagerType.USER_WEB);

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("excel");
		String teamId = multipartRequest.getParameter("teamId");
		if (!StringUtils.isEmpty(teamId)) {
			return nurseService.importNurseExcel(teamId, file);
		} else {
			return SysResult.error("teamId不能为空");
		}
	}

	/**
	 * 批量导入护工图片信息
	 */
	@RequestMapping("/importNursePictureZip")
	public SysResult importNursePictureZip(HttpServletRequest request) {
		// TODO
//		// 当前登录人
//		User user = LocalManager.getVal(LocalManagerType.USER_WEB);

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("zip");
		String teamId = multipartRequest.getParameter("teamId");
		if (!StringUtils.isEmpty(teamId)) {
			return nurseService.importNursePictureZip(teamId, file);
		} else {
			return SysResult.error("teamId不能为空");
		}
	}

	/**
	 * 护工详情 2017年10月23日14:24:57
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping("query/workerid")
	public SysResult getNurseWorkerInfo(@RequestBody Map<String, String> map) {
		if (StringUtils.isEmpty(map.get("workerId"))) {
			return SysResult.error("workerId：" + map.get("workerId") + "对应的护工信息不存在！");
		}
		String workerId = map.get("workerId");
		return nurseService.getNurseWorkerInfoById(workerId);
	}

	/**
	 * 获取护工详情
	 */
	@RequestMapping("/query")
	public SysResult findDetail(@RequestBody Map<String, Object> map) {
		if (!map.containsKey("id") || StringUtils.isEmpty(map.get("id").toString())) {
			return SysResult.error("对应的护工信息不存在！");
		}
		int id = Integer.parseInt(map.get("id").toString());
		return nurseService.findDetail(id);
	}

	/**
	 * 新建护工
	 * 
	 * @param nurseWorkerInfo
	 * @return
	 */
	@RequestMapping("/save")
	public SysResult add(@RequestBody @Valid NurseWorkerInfoDto nurseWorkerInfoDto) {
		if (StringUtils.isEmpty(nurseWorkerInfoDto.getWorkerType())) {
			nurseWorkerInfoDto.setWorkerType(WorkerTypeEnum._1.getKey());
		}

		// 1.0.7新增判断，若为临时护工：必填项为：姓名、性别、年龄、联系电话、护工编号、工作状态、护工类型、身份证
		if (!check1_0_7(nurseWorkerInfoDto)) {
			return SysResult.error("若为临时护工：必填项为：姓名、性别、年龄、联系电话、护工编号、工作状态、护工类型、身份证");
		}

		String errorMsg = checkMsg(nurseWorkerInfoDto);
		if (!StringUtils.isEmpty(errorMsg)) {
			return SysResult.error(errorMsg.substring(0, errorMsg.length() - 1));
		}
		// 获得当前登录用户信息
		// TODO
//    	ValidateUser user = LocalManager.getVal(LocalManagerType.USER_OUTWORKER);
//    	nurseWorkerInfoDto.setHospital(user.getUser().getTeamId());
//    	nurseWorkerInfoDto.setHospitalName(user.getUser().getTeamName());
		return nurseService.add(nurseWorkerInfoDto);
	}

	/**
	 * 修改护工基本信息
	 */
	@RequestMapping("/update")
	public SysResult modify(@RequestBody @Valid NurseWorkerInfoDto nurseWorkerInfoDto) {
		if (StringUtils.isEmpty(nurseWorkerInfoDto.getWorkerType())) {
			nurseWorkerInfoDto.setWorkerType(WorkerTypeEnum._1.getKey());
		}

		// 1.0.7新增判断，若为临时护工：必填项为：姓名、性别、年龄、联系电话、护工编号、工作状态、护工类型、身份证
		if (!check1_0_7(nurseWorkerInfoDto) || StringUtils.isEmpty(nurseWorkerInfoDto.getWorkerId())) {
			return SysResult.error("若为临时护工：必填项为：姓名、性别、年龄、联系电话、护工编号、工作状态、护工类型、身份证");
		}

		String errorMsg = checkMsg(nurseWorkerInfoDto);
		if (!StringUtils.isEmpty(errorMsg)) {
			return SysResult.error(errorMsg.substring(0, errorMsg.length() - 1));
		}
		if (StringUtils.isEmpty(nurseWorkerInfoDto.getWorkerId())) {
			return SysResult.error("护工编号不存在，无法修改。");
		}
		// 获得当前登录用户信息
		// TODO
//		ValidateUser user = LocalManager.getVal(LocalManagerType.USER_OUTWORKER);
//    	nurseWorkerInfoDto.setHospital(user.getUser().getTeamId());
//    	nurseWorkerInfoDto.setHospitalName(user.getUser().getTeamName());
		return nurseService.modify(nurseWorkerInfoDto);
	}

	/**
	 * 删除护工
	 */
	@RequestMapping("/delete")
	public SysResult delete(@RequestBody Map<String, Object> map) {
		if (!map.containsKey("id") || StringUtils.isEmpty(map.get("id").toString())) {
			return SysResult.error("对应的护工信息不存在！");
		}
		int id = Integer.parseInt(map.get("id").toString());
		return nurseService.delete(id);
	}

	/**
	 * 上传图片
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/img/upload")
	public SysResult upload(@RequestParam(value = "img") MultipartFile imgFile) throws Exception {
		return nurseService.upload(imgFile);
	}

	/**
	 * 健康证延期提醒列表
	 */
	@RequestMapping("/list-healthcert")
	public SysResult listHealthCert(@RequestBody NurseWorkerInfoRequestDto nurseWorkerInfoRequestDto) {
		// TODO
//		// 当前登录人信息
//		User courrentUser = LocalManager.getVal(LocalManagerType.USER_WEB);
		if (StringUtils.isEmpty(nurseWorkerInfoRequestDto.getTeamId())) {
			return SysResult.error("teamId不能为空");
		}

		if (!StringUtils.isEmpty(nurseWorkerInfoRequestDto.getDays())) {
			try {
				Integer.parseInt(nurseWorkerInfoRequestDto.getDays());
			} catch (Exception e) {
				return SysResultByPage.ok(0, "SUCCESS", new ArrayList<>(), 0);
			}
		}
		return nurseService.listHealthCert(nurseWorkerInfoRequestDto);
	}

	/**
	 * 健康证延期提醒--导出Excel
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/export-healthcert-excel")
	public void exportHealthCertExcel(@RequestBody NurseWorkerInfoRequestDto nurseWorkerInfoRequestDto,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO
//		// 当前登录人信息
//		User courrentUser = LocalManager.getVal(LocalManagerType.USER_WEB);

		try {
			List<NurseWorkerInfoHealthCertResponseDto> list = new ArrayList<>();
			if (!StringUtils.isEmpty(nurseWorkerInfoRequestDto.getDays())) {
				try {
					Integer.parseInt(nurseWorkerInfoRequestDto.getDays());
					list = nurseService.exportHealthCertExcel(nurseWorkerInfoRequestDto);
				} catch (Exception e) {
				}
			}
			if (StringUtils.isEmpty(nurseWorkerInfoRequestDto.getDays())) {
				nurseWorkerInfoRequestDto.setDays(null);
				list = nurseService.exportHealthCertExcel(nurseWorkerInfoRequestDto);
			}
			String finalFileName = URLEncoder.encode("健康证延期提醒" + TimeUtils.getTime(TimeType.yyyyMMddHHmmssSSS) + ".xls",
					"UTF8");
			response.addHeader("Content-Disposition", "attachment;filename=" + finalFileName);
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			ExcelUtil.getInstance().exportObj2Excel(toClient, list, NurseWorkerInfoHealthCertResponseDto.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 修改到期日
	 * 
	 * @return
	 */
	@RequestMapping("/modify-health-date")
	public SysResult modifyHealthDate(@RequestBody NurseWorkerInfoDto nurseWorkerInfoDto) {
		// TODO
		// User courrentUser = LocalManager.getVal(LocalManagerType.USER_WEB);
		return nurseService.modifyHealthDate(nurseWorkerInfoDto);
	}

	/**
	 * 提醒补办
	 * 
	 * @param nurseWorkerInfoDto
	 * @return
	 */
	@RequestMapping("/remind")
	public SysResult remind(@RequestBody NurseWorkerInfoDto nurseWorkerInfoDto) {
		// TODO
		// User courrentUser = LocalManager.getVal(LocalManagerType.USER_WEB);
		return nurseService.remind(nurseWorkerInfoDto);
	}

	/**
	 * 批量提醒
	 * 
	 * @param nurseWorkerInfoRequestDto
	 * @return
	 */
	@RequestMapping("/batch-remind")
	public SysResult batchRemind(@RequestBody NurseWorkerInfoRequestDto nurseWorkerInfoRequestDto) {
		// TODO
//		// 当前登录人信息
//		User courrentUser = LocalManager.getVal(LocalManagerType.USER_WEB);
		if (StringUtils.isEmpty(nurseWorkerInfoRequestDto.getDays())) {
			return SysResult.error("参数有误，请重新输入参数。");
		}
		if (!StringUtils.isEmpty(nurseWorkerInfoRequestDto.getDays())) {
			try {
				Integer.parseInt(nurseWorkerInfoRequestDto.getDays());
			} catch (Exception e) {
				return SysResult.error("补办剩余天数必须为整数");
			}
		}
		if (nurseWorkerInfoRequestDto.getRemindStatus() == true) {
			nurseWorkerInfoRequestDto.setRemindStatus(null);
		}
		return nurseService.batchRemind(nurseWorkerInfoRequestDto);
	}

	/**
	 * 下载文档pdf
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/download-pdf")
	public void downloadPdf(@RequestBody Map<String, Object> map, HttpServletResponse response) throws Exception {
		// TODO
//		// 当前登录人信息
//		User courrentUser = LocalManager.getVal(LocalManagerType.USER_WEB);
		List<Integer> ids = (List<Integer>) map.get("ids");
		String teamId = (String) map.get("teamId");
		if (StringUtils.isEmpty(ids) || ids.size() <= 0) {
			throw new Exception("请选择需要下载的护理员信息");
		}
		if (StringUtils.isEmpty(teamId)) {
			throw new Exception("teamId不能为空");
		}
		nurseService.downloadPdf(teamId, ids.toArray(new Integer[ids.size()]), response);
	}

	////////////////////////////////////////////////////

	/**
	 * 校验信息
	 * 
	 * @param nurseWorkerInfo
	 * @return
	 */
	private String checkMsg(NurseWorkerInfoDto info) {
		StringBuffer sb = new StringBuffer();
		if (!info.getWorkerType().equals(WorkerTypeEnum._2.getKey())) {
			if (info.getPhone().length() > 12 || info.getPhone().length() <= 0) {
				sb.append("手机号输入错误，");
			}
			if (info.getContactPhone().length() > 12 || info.getContactPhone().length() <= 0) {
				sb.append("紧急联系人手机号输入错误，");
			}
			if (!StringUtils.isEmpty(info.getBankCard()) && !StringUtils.isBankCard(info.getBankCard())) {
				sb.append("银行卡号输入错误，");
			}
			if (!StringUtils.isEmpty(info.getIdCard()) && !StringUtils.isCard(info.getIdCard())) {
				sb.append("身份证号输入错误，");
			}
		}
		return sb.toString();
	}

	/**
	 * 1.0.7新增判断，若为临时护工：必填项为：姓名、性别、年龄、联系电话、护工编号、工作状态、护工类型、身份证 @Title:
	 * check1_0_7 @return boolean @version V1.0.7 @throws
	 */
	private boolean check1_0_7(NurseWorkerInfoDto dto) {
		if (dto.getWorkerType().equals(WorkerTypeEnum._2.getKey())) {
			// 姓名
			if (StringUtils.isEmpty(dto.getWorkerName()))
				return false;
			// 性别
			if (StringUtils.isEmpty(dto.getSex()))
				return false;
			// 年龄
			if (StringUtils.isEmpty(dto.getBirthDate()))
				return false;
			// 联系电话
			if (StringUtils.isEmpty(dto.getPhone()))
				return false;
			// 工作状态
			if (StringUtils.isEmpty(dto.getWorkStatus()))
				return false;
			// 护工类型
			if (StringUtils.isEmpty(dto.getWorkerType()))
				return false;
			// 身份证号
			if (StringUtils.isEmpty(dto.getIdCard()))
				return false;
		}
		return true;
	}

}
